package com.adv.ems.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.adv.ems.db.entity.CollectPointDO;
import com.adv.ems.db.entity.SystemWarningDO;
import com.adv.ems.enums.CollectPointWarningTypeEnum;
import com.adv.ems.enums.DateTypeEnum;
import com.adv.ems.model.dto.QueryPointEnergyResultDTO;
import com.adv.ems.model.dto.UserSubjectInfo;
import com.adv.ems.model.vo.FullIndexBasicInfoVO;
import com.adv.ems.model.vo.FullWarningInfoVO;
import com.adv.ems.service.FullScreenService;
import com.adv.ems.service.WarningService;
import com.adv.ems.utils.EmsUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FullScreenServiceImpl extends BaseServiceImpl implements FullScreenService {
    @Resource
    WarningService warningService;

    @Override
    public FullIndexBasicInfoVO basicInfo(String acceptLanguage) {
        FullIndexBasicInfoVO result = new FullIndexBasicInfoVO();
        UserSubjectInfo userSubjectInfo = getUserSubjectInfo(getCurrentUser());
        setBasicInfo(result, userSubjectInfo);
        setEnergyCompare(result);
        return result;
    }

    @Override
    public FullWarningInfoVO warning(String acceptLanguage) {
        FullWarningInfoVO result = new FullWarningInfoVO();
        UserSubjectInfo userSubjectInfo = getUserSubjectInfo(getCurrentUser());
        FullIndexBasicInfoVO pointIds = new FullIndexBasicInfoVO();
        setBasicInfo(pointIds, userSubjectInfo);
        List<String> types = ListUtil.of(CollectPointWarningTypeEnum.SAFE_UP.name(), CollectPointWarningTypeEnum.SAFE_LOW.name(), CollectPointWarningTypeEnum.OFFLINE.name());
        List<SystemWarningDO> list = warningService.getTodayUnReadLastWarning(pointIds.getPointIds(), CollectPointDO.class, types, 10);
        list.forEach(l -> {
            FullWarningInfoVO.Info info = new FullWarningInfoVO.Info();
            info.setId(l.getId());
            String title = l.getType().equals(CollectPointWarningTypeEnum.OFFLINE.name()) ? "掉线提醒": "安全提醒";
            info.setTitle(title);
            info.setContent(l.getMsg());
            info.setTime(DateUtil.format(l.getUpdateTime(), "HH:mm:ss"));
            result.getList().add(info);
        });
        return result;
    }


    private void setBasicInfo(FullIndexBasicInfoVO result, UserSubjectInfo userSubjectInfo) {
        if (CollectionUtil.isNotEmpty(userSubjectInfo.getInstitute())) {
            List<Long> ids = virtualInstituteDeal(ListUtil.of(userSubjectInfo.getInstitute().get(0)));
            List<Long> buildingIds = ids.stream().flatMap(id -> getBuildingIdsByInstitution(id).stream()).collect(Collectors.toList());
            List<Long> meterIds = ids.stream().flatMap(id -> getAllMeterIdsByInstitution(id).stream()).collect(Collectors.toList());
            List<Long> pointIds = getAllPointIds(meterIds, null, null, null, null);
            result.setBuildingIds(buildingIds);
            result.setMeterIds(meterIds);
            result.setPointIds(pointIds);
        }else if (CollectionUtil.isNotEmpty(userSubjectInfo.getBuilding())){
            Long id = userSubjectInfo.getBuilding().get(0);
            List<Long> meterIds = getAllMeterIdsByBuilding(id);
            List<Long> pointIds = getAllPointIds(meterIds, null, null, null, null);
            result.setBuildingIds(ListUtil.of(id));
            result.setMeterIds(meterIds);
            result.setPointIds(pointIds);
        }else if (CollectionUtil.isNotEmpty(userSubjectInfo.getDepartment())){
            Long id = userSubjectInfo.getDepartment().get(0);
            List<Long> meterIds = getMeterIdsByDepartment(id);
            List<Long> pointIds = getAllPointIds(meterIds, null, null, null, null);
            result.setMeterIds(meterIds);
            result.setPointIds(pointIds);
        }
    }

    private void setEnergyCompare(FullIndexBasicInfoVO result) {
        List<Long> pointIds = result.getPointIds();
        //今天
        Date endNow = new Date();
        Date fromNow = DateUtil.beginOfDay(new Date());
        List<QueryPointEnergyResultDTO> nowList = getPointEnergy(DateTypeEnum.day, fromNow, endNow, pointIds);
        QueryPointEnergyResultDTO nowData = QueryPointEnergyResultDTO.sumAll(nowList);
        //昨天
        Date endLast = new Date(endNow.getTime() - Duration.ofDays(1).toMillis());
        Date fromLast = DateUtil.beginOfDay(endLast);
        List<QueryPointEnergyResultDTO> lastList = getPointEnergy(DateTypeEnum.day, fromLast, endLast, pointIds);
        QueryPointEnergyResultDTO lastData = QueryPointEnergyResultDTO.sumAll(lastList);

        Double nowStandValue = nowData.getIncreaseStandValue();
        Double lastStandValue = lastData.getIncreaseStandValue();
        result.setIncreaseCashValue(nowData.getIncreaseCashValue());
        result.setIncreaseStandValue(nowData.getIncreaseStandValue());
        if (lastStandValue <= 0) {
            result.setCompareYesterday("-");
        }else if (nowStandValue <= 0){
            result.setCompareYesterday("-");
        }else {
            double v = (nowData.getIncreaseStandValue() - lastStandValue) * 100D / lastStandValue;
            if (v < 0) {
                String format = EmsUtil.valueFormat(-1 * v);
                result.setCompareYesterday(format + "%");
                result.setCompareState(-1);
            }else if (v > 0) {
                String format = EmsUtil.valueFormat(v);
                result.setCompareYesterday(format + "%");
                result.setCompareState(1);
            }else {
                result.setCompareYesterday("持平");
            }
        }
    }
}
